import env from './env.js'
import store from '@/common/utils/store'

let localforage = require('localforage');
import {
	loading
} from './index'
import {
	Message,
	Notification
} from 'element-ui';

let messageInstance = null;
// 网络请求封装
const api = obj => {
	const url = obj.url
	const host = obj.host || env.base;
	const data = obj.data
	const isAuth = obj.auth == false ? false : true;
	const method = obj.method
	const successCode = obj.successCode || env.successCode
	//是否显示loading
	let hasLoading = true;
	if (typeof obj.hasLoading !== 'undefined' && typeof obj.hasLoading == 'boolean') {
		hasLoading = obj.hasLoading;
	}
	// 是否显示提示信息
	const showToast = obj.showToast === false ? false : true
	let header = obj.header ? obj.header : {
		'Content-Type': 'application/json;charset=UTF-8',
	};
	header['withCredentials'] = true;
	if (isAuth) {
		header.Authorization = uni.getStorageSync("token") || ''
	}
	if (hasLoading) {
		loading();
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: host + url,
			method: method || 'get',
			data: data,
			header: header,
			success: res => {
				if (hasLoading) {
					loading(true);
				}
				if (res.data.code === successCode) {
					resolve(res.data)
				} else {
					if (res.data.errorCode === env.reLoginCode) {
						messageError('登录凭证失效，请重新登录！', true);
						store.commit("logout");
						uni.redirectTo({
							url: env.loginPage || '/'
						})
					} else {
						if (showToast) {
							messageError(res.data.errMsg || '网络异常，请稍后重试', true);
						}
					}
					reject(res.data)
				}
			},
			fail: err => {
				if (hasLoading) {
					loading(true);
				}
				if (showToast) {
					messageError("网络异常，请稍后重试", true);
				}
				reject(err)
			}
		})
	})
}


const login = async (data, callback, error) => {
	loading();
	data = data || {};
	let header = {
		'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
		'Authorization': ''
	};
	wx.request({
        url: `${env.base}/oauth/token`,
        method: 'post',
        header: header,
        data: data,
        success: res => {
            loading(true);
            if (res.data.code === env.successCode) {
                uni.setStorageSync('token', 'Bearer ' + res.data.data.access_token)
                uni.setStorageSync('atoken', res.data.data.access_token)
                typeof callback === "function" && callback(res.data.data)
            } else {
                console.log(res);
                messageError(res.data.errMsg || '网络异常，请稍后重试');
                typeof error === "function" && error(res.data)
            }
        },
        fail: res => {
            loading(true);
			messageError("网络异常，请稍后重试");
			typeof error === "function" && error(res)
		}
	})
}

module.exports = {
	api: api,
	login: login
}


const messageError = (message, close) => {
	if (messageInstance != null) {
		if (!close) {
			return;
		}
		Notification.closeAll();
		messageInstance = null;
	}
	messageInstance = Notification.error({
		title: "消息通知",
		message: message,
		onClose(ins) {
			messageInstance = null;
		}
	});
}
